import os
import time
import sys
import logging
import socket
import ctypes
import platform
from datetime import datetime, timedelta
from ntplib import NTPClient

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s: %(message)s',
    handlers=[
        logging.FileHandler('time_sync.log'),
        logging.StreamHandler()
    ]
)


def set_system_time(target_time):
    """设置系统时间（需要管理员权限）"""
    system = platform.system()
    try:
        if system == 'Windows':
            # Windows系统时间设置
            kernel32 = ctypes.windll.kernel32
            system_time = target_time.timetuple()

            class SYSTEMTIME(ctypes.Structure):
                _fields_ = [
                    ("wYear", ctypes.c_short),
                    ("wMonth", ctypes.c_short),
                    ("wDayOfWeek", ctypes.c_short),
                    ("wDay", ctypes.c_short),
                    ("wHour", ctypes.c_short),
                    ("wMinute", ctypes.c_short),
                    ("wSecond", ctypes.c_short),
                    ("wMilliseconds", ctypes.c_short),
                ]

            new_time = SYSTEMTIME()
            new_time.wYear = system_time.tm_year
            new_time.wMonth = system_time.tm_mon
            new_time.wDay = system_time.tm_mday
            new_time.wHour = system_time.tm_hour
            new_time.wMinute = system_time.tm_min
            new_time.wSecond = system_time.tm_sec
            kernel32.SetLocalTime(ctypes.byref(new_time))
        else:
            # Linux/Mac系统时间设置
            libc = ctypes.CDLL('libc.so.6')
            timeval = (ctypes.c_long * 2)()
            timeval[0] = int(target_time.timestamp())
            timeval[1] = 0
            libc.settimeofday(timeval, None)

        logging.info(f"系统时间已更新至: {target_time}")
        return True
    except Exception as e:
        logging.error(f"时间设置失败: {str(e)}")
        return False


# 在已有导入中添加
import argparse


def sync_time(server):  # 修改函数定义
    """同步时间主函数"""
    client = NTPClient()
    try:
        response = client.request(server)  # 使用传入的server参数
        ntp_time = datetime.fromtimestamp(response.tx_time)
        return set_system_time(ntp_time)
    except socket.gaierror:
        logging.error("无法解析NTP服务器地址")
    except Exception as e:
        logging.error(f"NTP请求失败: {str(e)}")
    return False


if __name__ == '__main__':
    # 检测管理员权限
    if platform.system() == 'Windows':
        if not ctypes.windll.shell32.IsUserAnAdmin():
            logging.error("请以管理员权限运行此程序")
            sys.exit(1)
    elif os.geteuid() != 0:
        logging.error("请使用sudo权限运行此程序")
        sys.exit(1)

    # 新增参数解析（放在文件末尾的__main__部分）
    parser = argparse.ArgumentParser(description='系统时间同步工具')
    parser.add_argument('--server', type=str, default='ntp.aliyun.com',
                        help='NTP服务器地址（默认：ntp.aliyun.com）')
    parser.add_argument('--interval', type=int, default=60,
                        help='成功同步后的间隔时间（秒，默认：60）')
    parser.add_argument('--retry', type=int, default=300,
                        help='失败后的重试间隔（秒，默认：300）')
    args = parser.parse_args()
    while True:
        logging.info(f"开始时间同步，使用服务器：{args.server}")
        if sync_time(args.server):  # 传递服务器参数
            logging.info(f"同步成功，{args.interval}秒后再次同步")
            time.sleep(args.interval)
        else:
            logging.warning(f"同步失败，{args.retry}秒后重试")
            time.sleep(args.retry)

# # 修改主循环中的调用
# while True:
#     logging.info("开始时间同步...")
#     if sync_time():
#         logging.info("同步成功")
#     else:
#         logging.warning("同步失败，将在2分钟后重试")
#         time.sleep(120)  # 失败后等待2分钟
#         continue
#
#     time.sleep(60 * 1)  # 成功同步后等待1分钟
